package com.xishu.client;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dm.model.v20151123.SingleSendMailRequest;
import com.aliyuncs.dm.model.v20151123.SingleSendMailResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.xishu.config.Config;
import com.xishu.entity.customer.Customer;
import com.xishu.entity.customer.VipRenewEmailTemplate;
import com.xishu.service.CustomerService;
import com.xishu.util.DateUtil;
import com.xishu.util.Tools;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.hibernate.event.internal.DefaultAutoFlushEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.stream.Collectors;

public class CustomerEmailClient implements Tools {
    private static CustomerEmailClient instance = new CustomerEmailClient();
    private static Logger logger = LoggerFactory.getLogger(CustomerEmailClient.class);

    private CustomerEmailClient() {
    }

    public static CustomerEmailClient getInstance() {
        return instance;
    }

    /**
     * 给某一个用户发送邮件
     *
     * @param senderName
     * @param emailAddress
     * @param title
     * @param content
     * @param customer
     */
    public void sendEmail(String senderName, String emailAddress, String title, String content, Customer customer) throws Exception {
        sendEmail(senderName, emailAddress, title, content, customer, null);
    }

    /**
     * 给某一个用户发送邮件
     *
     * @param senderName
     * @param emailAddress
     * @param title
     * @param content
     * @param customer
     */
    public void sendEmail(String senderName, String emailAddress, String title, String content, Customer customer, VipRenewEmailTemplate vipRenewEmailTemplate) throws Exception {
        if (content.contains("${sex}")) {
            content = content.replace("${sex}", getSex(customer));
        }

        if (content.contains("${phone}")) {
            content = content.replace("${phone}", getPhone(customer));
        }

        if (content.contains("${email}")) {
            content = content.replace("${email}", getEmail(customer));
        }

        if (content.contains("${nickname}")) {
            content = content.replace("${nickname}", getNickName(customer));
        }

        if (content.contains("${age}")) {
            content = content.replace("${age}", getAge(customer));
        }

        if (content.contains("${preference}")) {
            content = content.replace("${preference}", getPreference(customer));
        }

        if (content.contains("${birthday}")) {
            content = content.replace("${birthday}", getBirthday(customer));
        }

        if (content.contains("${renewurl}") && vipRenewEmailTemplate != null) {
            Config config = Config.getInstance();

            if (isNotEmpty(vipRenewEmailTemplate.getStripeAk())) {
                content = content.replace("${renewurl}",
                        String.format("%s/customer/index.html/#/pages/renew/vipdetail?cid=%s&cuid=%s&stripeAk=%s&vipEndTime=%s",
                                config.getEndPoint(), customer.getCompanyId(), customer.getId(), vipRenewEmailTemplate.getStripeAk(), customer.getVipEndTime()));
            } else {
                logger.info("do not config the renewurl {}", customer.getCompanyId());
                content = content.replace("${renewurl}", "");
            }
        }

        sendEmail(senderName, emailAddress, title, content);
    }

    /**
     * 获取性别
     *
     * @param customer
     * @return
     */
    public String getSex(Customer customer) {
        if (getInt(customer.getSex()) == 1) {
            return "先生/Sir";
        } else if (getInt(customer.getSex()) == 2) {
            return "女士/lady";
        } else {
            return "未选择/unselect";
        }
    }

    /**
     * 电话号码
     *
     * @param customer
     * @return
     */
    public String getPhone(Customer customer) {
        if (isNotEmpty(customer.getPhone())) {
            return customer.getPhone();
        } else {
            return "未选择/unselect";
        }
    }

    /**
     * 获取邮件
     *
     * @param customer
     * @return
     */
    public String getEmail(Customer customer) {
        if (isNotEmpty(customer.getEmail())) {
            return customer.getEmail();
        } else {
            return "未选择/unselect";
        }
    }

    /**
     * 获取昵称
     *
     * @param customer
     * @return
     */
    public String getNickName(Customer customer) {
        if (isNotEmpty(customer.getNickName())) {
            return customer.getNickName();
        } else {
            return "未选择/unselect";
        }
    }

    /**
     * 获取年龄
     *
     * @param customer
     * @return
     */
    public String getAge(Customer customer) {
        if (customer.getBirthDay() != null) {
            int currentYear = Integer.parseInt(DateUtil.format(System.currentTimeMillis(), "yyyy"));
            int bornYear = Integer.parseInt(DateUtil.format(customer.getBirthDay(), "yyyy"));
            return String.valueOf(currentYear - bornYear);
        } else {
            return "未选择/unselect";
        }
    }

    /**
     * 获取就餐偏好
     *
     * @param customer
     * @return
     */
    public String getPreference(Customer customer) {
        if (isNotEmpty(customer.getPreferenceList())) {
            List<Integer> preferenceList = customer.getPreferenceList();
            List<String> stringList = preferenceList.stream().map(p -> {
                return String.format("%s/%s", CustomerService.PREFERENCE_MAP_ZH.get(p), CustomerService.PREFERENCE_MAP_EN.get(p));
            }).collect(Collectors.toList());

            return StringUtils.join(stringList, ",");
        } else {
            return "未选择/unselect";
        }
    }

    /**
     * 获取生日
     *
     * @param customer
     * @return
     */
    public String getBirthday(Customer customer) {
        if (isNotEmpty(customer.getBirthDay())) {
            Long birthDay = customer.getBirthDay();
            return DateUtil.format(birthDay, "MM-dd");
        } else {
            return "未选择/unselect";
        }
    }


    /**
     * 发送邮件
     *
     * @param senderName
     * @param emailAddress
     * @param title
     * @param content
     */
    public void sendEmail(String senderName, String emailAddress, String title, String content) throws Exception {
        DefaultProfile.addEndpoint("dm.ap-southeast-1.aliyuncs.com", "ap-southeast-1", "Dm", "dm.ap-southeast-1.aliyuncs.com");
        IClientProfile profile = DefaultProfile.getProfile("ap-southeast-1", "LTAI5tQNNxKE86csecB3f2v1", "ys771qzh9qkaBph9r3ueYSwYeAHFyf");
        IAcsClient client = new DefaultAcsClient(profile);
        SingleSendMailRequest request = new SingleSendMailRequest();
        request.setAccountName("notice@notice.dolatech.net");

        if (senderName == null || senderName.length() == 0) {
            senderName = "DoLA Technology";
        }

        request.setFromAlias(senderName);
        request.setAddressType(1);
        request.setReplyToAddress(true);
        request.setToAddress(emailAddress);
        //可以给多个收件人发送邮件，收件人之间用逗号分开，批量发信建议使用BatchSendMailRequest方式
        //request.setToAddress("邮箱1,邮箱2");
        request.setSubject(title);
        request.setHtmlBody(content);
        logger.info("will send email to {}", emailAddress);
        SingleSendMailResponse httpResponse = client.getAcsResponse(request);
        logger.info("httpResponse is {}", JSONObject.fromObject(httpResponse));
    }
}
